/**
 * Created by Administrator on 2015/1/7.
 */
    // not supported by IE < 8 or any other browser which does not support DOM prototypes.
    // ie < 8 appendChild is not function,
    // but trusty setInterval method if typeof document.body.appendChild !== 'function'
var EP = Element.prototype,
    APPEND_CHILD = EP.appendChild;

EP.appendChild = function() {
    console.log('append child before');
    return APPEND_CHILD.apply(this, arguments);
};

// http://stackoverflow.com/questions/7692730/dom-mutation-event-in-jquery-or-vanilla-javascript
var DomWatcher = function(root, callback){
    // IE < 8 不支持 DOM prototypes, 因此无法使用 HTMLDivElement.prototype.appendChild
    var __appendChild = document.body.appendChild;

    var patch = function(node) {
        if(typeof node.appendChild !== 'undefined' && node.nodeName !== '#text'){
            node.appendChild = function(incomingNode){
                callback(node, incomingNode);
                patch(incomingNode);
                walk(incomingNode);
                // IE < 8 appendChild 不是 function, 不支持 apply, call !! 测试发现object 居然支持apply, call
                return __appendChild.call(node, incomingNode);
            };
        }
        walk(node);
    };

    var walk = function(node){
        var i = node.childNodes.length;
        while(i--){
            patch(node.childNodes[i]);
        }
    };

    patch(root);

};

DomWatcher(document.body, function(targetElement, newElement){
    console.log('append detected');
});

/*
$('#container ul li').first().append('<div><p>hi</p></div>');
$('#container ul li div p').append('<a href="#foo">bar</a>');
 */
